import json
import time

from flask import request, jsonify
from flask_script import Manager,Server
from flask_migrate import Migrate,MigrateCommand
from app import db,app
#注册蓝图
from util.myjwt import myjwt
from util.myredis import r
from views.user import user_blue
app.register_blueprint(user_blue)

# 生成管理工具对象
manager = Manager(app)
# 添加服务器运行指令
manager.add_command("runserver",Server(host='0.0.0.0',use_debugger=True))

# 数据库迁移
Migrate(app,db)
# 添加数据库的操作指令
manager.add_command("db", MigrateCommand)

@app.before_request
def before_request():
    white = ['/login']
    url = request.path
    print(url)
    if url not in white:
        # 获取token
        token = request.headers.get('token')
        print(token)
        try:
            flag = myjwt.check(token)
            if flag == True:
                # 解析验证时间
                payload = myjwt.jwt_decode(token)
                ptime = payload['data']['exp']
                now = time.time()
                if int(now) - int(ptime) > 3600:
                    return jsonify({"code": 402, "msg": "token已过期"})
                key = "user_out"
                res = r.sortedset_getall(key)
                for i in res:
                    if token == i.decode():
                        return jsonify({'code': 409, "msg": "用户已退出"})
                key = 'role_id' + str(payload['data']['role_id'])

                urls = r.get_str(key)
                url = url.split('?')
                if url[0] not in json.loads(urls):
                    return jsonify({'code': 408, "msg": "无接口权限"})

                # 接口权限验证
                #  {"data": {"name": "zs", "userid": 1,'exp':}}
        except:
            return jsonify({"code": 401, "msg": "后端错误"})



#如果是以此脚本作为主脚本程序，就执行
if __name__ == '__main__':
    # manager.run()
    app.run(port=8000)
